#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    for (int i = 0 ; i < 3 ;++i ) {
        readThreadVector.emplace_back(new ReadThread(&readWriteLock));
        writeThreadVector.emplace_back(new WriteThread(&readWriteLock));
    }


}

Widget::~Widget()
{
    on_btnStop_clicked();
   //等待线程结束
    auto it = readThreadVector.begin();
    for(;it != readThreadVector.end() ; ++it){
        (*it)->wait();
    }

    //等待线程结束
    auto it2 = writeThreadVector.begin();
    for(;it2 != writeThreadVector.end() ; ++it2){
        (*it2)->wait();
    }

    qDeleteAll(readThreadVector.begin(),readThreadVector.end());
    qDeleteAll(writeThreadVector.begin(),writeThreadVector.end());
    delete ui;

}


void Widget::on_btnRead_clicked()
{
    //允许同时读
     auto it = readThreadVector.begin();
     for(;it != readThreadVector.end() ; ++it){
         (*it)->start();
     }
}

void Widget::on_btnWrite_clicked()
{
    //不允许同时写
     auto it2 = writeThreadVector.begin();
     for(;it2 != writeThreadVector.end() ; ++it2){
         (*it2)->start();
     }

}

void Widget::on_btnWriteNotRead_clicked()
{
     //写的时候不能读
     auto it2 = writeThreadVector.begin();
     for(;it2 != writeThreadVector.end() ; ++it2){
         (*it2)->start();
     }
    QThread::usleep(100); //确保先启动写线程

     auto it = readThreadVector.begin();
     for(;it != readThreadVector.end() ; ++it){
         (*it)->start();
     }

}

void Widget::on_btnReadNotWrite_clicked()
{
    //读的时候不允许写
     auto it = readThreadVector.begin();
     for(;it != readThreadVector.end() ; ++it){
         (*it)->start();
     }

     QThread::usleep(100); //确保先启动读线程

     auto it2 = writeThreadVector.begin();
     for(;it2 != writeThreadVector.end() ; ++it2){
         (*it2)->start();
     }

}



void Widget::on_btnStop_clicked()
{
    auto it = readThreadVector.begin();
    for(;it != readThreadVector.end() ; ++it){
        (*it)->setStop();
    }

    //等待线程结束
    auto it2 = writeThreadVector.begin();
    for(;it2 != writeThreadVector.end() ; ++it2){
        (*it2)->setStop();
    }
}
